package com.ssy.lingxi.member.merchant.api.handler.validator;

import com.ssy.lingxi.member.merchant.api.handler.annotation.TreeMenuKeyAnno;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;

/**
 * 树形菜单key值校验处理类
 * @author 万宁
 * @version 2.0.0
 * @date 2020-06-16
 */
public class TreeMenuKeyValidator implements ConstraintValidator<TreeMenuKeyAnno, String> {
    private boolean required = false;

    @Override
    public void initialize(TreeMenuKeyAnno constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if(!required) {
            return true;
        }

        if (value == null || "".equals(value) || value.contains("--") || value.startsWith("-") || value.endsWith("-")) {
            return false;
        }

        String[] strs = value.split("-");
        return Arrays.stream(strs).allMatch(s -> s.matches("[0-9]+"));
    }
}
